import {computed, ref} from "vue";
import {current} from "./usePlayer";

const _lyric = ref<Array<Record<string, any>>>([]);
const lyric_time_reg = /\[(\d+):(\d+)\.(\d+)\](.*)/;

const setLyric = (content: string) => {
    let lyrics = content.split('\n').filter(item => item.match(lyric_time_reg));
    _lyric.value = lyrics.map(item => {
        // @ts-ignore
        const [$1, min, sec, ms, content] = Array.from(item.match(lyric_time_reg));
        // @ts-ignore
        const time = min * 60 + sec * 1 + ms * 0.001;
        return {
            time,
            content,
            active: false
        }
    });
};

const lyric = computed(() => {
    const result = [];
    let hasActive = false;
    for (let i = _lyric.value.length - 1; i >= 0; i--) {
        let item = {..._lyric.value[i]};
        if (item.time <= current.value) {
            item.active = !hasActive;
            hasActive = true;
        } else {
            item.active = false;
        }
        result.unshift(item)
    }
    return result;
});

export {
    setLyric,
    lyric
}
